package com.zzyl.nursing.service.impl;


import java.time.*;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.dto.ReservationAddDTO;
import com.zzyl.nursing.dto.ReservationCountDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 预约信息Service业务层处理
 * 
 * @author lp
 * @date 2025-10-23
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper,Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        return save(reservation)?1:0;
    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return updateById(reservation)?1:0;
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除预约信息信息
     * 
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Override
    public int todayCancelledCountByUserId( LocalDateTime startTime, LocalDateTime endTime) {
        if ( startTime == null || endTime == null) {
            throw new IllegalArgumentException("时间范围不能为空");
        }


        return reservationMapper.countByUserIdAndStatusAndTimeRange(
                2, //2是取消
                startTime,
                endTime
        );
    }
    // 可选预约时间段
    private static final List<LocalTime> TIME_SLOTS = List.of(
            LocalTime.of(8, 0),
            LocalTime.of(8, 30),
            LocalTime.of(9, 0),
            LocalTime.of(9, 30),
            LocalTime.of(10, 0),
            LocalTime.of(10, 30),
            LocalTime.of(11, 0),
            LocalTime.of(11, 30),
            LocalTime.of(12, 0),
            LocalTime.of(12, 30),
            LocalTime.of(13, 0),
            LocalTime.of(13, 30),
            LocalTime.of(14, 0),
            LocalTime.of(14, 30),
            LocalTime.of(15, 0),
            LocalTime.of(15, 30),
            LocalTime.of(16, 0),
            LocalTime.of(16, 30),
            LocalTime.of(17, 0),
            LocalTime.of(17, 30),
            LocalTime.of(18, 0)

    );

   //默认六次
    private static final Integer TOTAL_QUOTA = 6;

    @Override
    public List<ReservationCountDTO> remainingCountOnDate(Long time) {
        List<ReservationCountDTO> result = new ArrayList<>();
        LocalDate date = Instant.ofEpochMilli(time)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        for (LocalTime timeSlot : TIME_SLOTS) {
            LocalDateTime reservationTime = LocalDateTime.of(date, timeSlot);
            int reservedCount = reservedCount(reservationTime);
            int remainingCount = TOTAL_QUOTA - reservedCount;
            if (remainingCount != TOTAL_QUOTA) {
                ReservationCountDTO dto = new ReservationCountDTO();
                dto.setTime(reservationTime);
                dto.setCount(remainingCount);
                result.add(dto);
            }
        }
        return result;
    }

    @Override
    public void AddSchedule(ReservationAddDTO addDTO,Long userId) {
        if (!addDTO.getType().equals(0)||addDTO.getType().equals(1)) {
            throw new RuntimeException("不支持该预约类型");
        }
        LocalDateTime reservationTime = addDTO.getTime();
        // 预约时间不能早于当前时间
        if (reservationTime.isBefore(LocalDateTime.now())) {
            throw new RuntimeException("预约时间不能早于当前时间");
        }
        LocalTime timeSlot = reservationTime.toLocalTime();
        if (!TIME_SLOTS.contains(timeSlot)) {
            //该时间段不支持预约
            throw new RuntimeException("该时间段不支持预约");
        }
        int reservedCount = reservedCount(reservationTime);
           //该时间段已约满
        if (reservedCount >= TOTAL_QUOTA) {
            throw new RuntimeException("该时间段已约满");
        }
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getMobile,addDTO.getMobile())
                .eq(Reservation::getTime, reservationTime)
                .ne(Reservation::getStatus, 2);
        long repeatCount = reservationMapper.selectCount(queryWrapper);
        if (repeatCount > 0) {
            //你已预约该时间段
            throw new RuntimeException("你已预约该时间段");
        }

        Reservation reservation = new Reservation();
        reservation.setName(addDTO.getName());
        reservation.setMobile(addDTO.getMobile());
        reservation.setTime(reservationTime);
        reservation.setVisitor(addDTO.getVisitor());
        reservation.setType(addDTO.getType());
        reservation.setStatus(0);
        reservation.setCreateBy(userId.toString());
        BeanUtils.copyProperties(addDTO, reservation);
        reservationMapper.insert(reservation);
    }

    @Override
    public IPage<Reservation> selectBookingPage(Page<Reservation> page,Long userId,Integer status) {
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getCreateBy, userId.toString());
        if (status != null) {
            queryWrapper.eq(Reservation::getStatus, status);
        }
        queryWrapper.orderByDesc(Reservation::getCreateTime);

        return reservationMapper.selectPage(page, queryWrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancelBooking(Long id) {
        Reservation reservation = reservationMapper.selectById(id);
        if (reservation == null) {
            throw new RuntimeException("预约记录不存在");
        }

        // 0-待生效，1-进行中，2-已取消，3-已完成）
        if (reservation.getStatus() == 2) {
            throw new RuntimeException("该预约已取消");
        }
        if (reservation.getStatus() == 3) {
            throw new RuntimeException("该预约已完成，无法取消");
        }


        LocalDateTime now = LocalDateTime.now();

        Reservation reservation1 = new Reservation();
        reservation1.setId(id);
        reservation1.setStatus(2);
        reservation1.setRemark("用户取消");
        int rows = reservationMapper.updateById(reservation1);
        return rows > 0;
    }

    @Override
    public int markReservationsasExpired() {
        LambdaUpdateWrapper<Reservation> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Reservation::getStatus, 0)
                .lt(Reservation::getTime, LocalDateTime.now())
                .set(Reservation::getStatus,3);

        return reservationMapper.update(null, updateWrapper);
    }


    private int reservedCount(LocalDateTime reservationTime) {

        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getTime, reservationTime)
                .ne(Reservation::getStatus, 2);

        return reservationMapper.selectCount(queryWrapper).intValue();
    }

}
